# -*- coding: utf-8 -*-
import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
import json, os, base64, requests, time
from io import BytesIO
from PIL import Image
from sys import version_info
from bot_log import BotLogger

logger = BotLogger(os.path.basename(__file__), logname=2).getLogger()


class C_YDM_HTTP(object):
    """云打码图片验证码识别类"""
    def __init__(self):
        self.uname = 'workai'
        self.pwd = '123456789.'

    def base64_api(self, uname, pwd, img, typeid):
        img = img.convert('RGB')
        buffered = BytesIO()
        img.save(buffered, format="JPEG")
        if version_info.major >= 3:
            b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
        else:
            b64 = str(base64.b64encode(buffered.getvalue()))
        # 验证码类型(默认 3 数英混合)：16:汉字 14:图片旋转 11:计算题 7:无感学习，4:闪动GIF，3:数英混合，2:纯英文，1:纯数字.
        data = {"username": uname, "password": pwd, "image": b64, "typeid": typeid}
        result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
        if result['success']:
            return result["data"]["result"]
        else:
            return result["message"]

    def get_code(self, filename, typeid):
        """获取验证码公共函数"""

        logger.info("Start Get CertCode ...")
        img_path = filename
        img = Image.open(img_path)
        result = self.base64_api(uname=self.uname, pwd=self.pwd, img=img, typeid=typeid)
        if result != '':
            logger.info("CertCode Get Success...")
            # self.delete_code(filename)
            return result
        else:
            logger.error("CertCode Get Faile...")
            self.delete_code(filename)
            return ''

    def delete_code(self, filename):
        if os.path.exists(filename):
            logger.info("Delete CertCode Image ...")
            os.remove(filename)
